<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 商品品牌类
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-03-10 09:49:10 +0800 (一, 2014-03-10) $
 * @version : $Id: brand_model.php 62 2014-03-10 01:49:10Z spike $
 * @rev     : $Revision: 62 $
 */
class Brand_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    // --------------------------------------------------------------------
    
    /**
     * [获得一个品牌]
     * @param  [string]     $brand_sn
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @return [array/false]
     */
    public function get_brand($brand_sn, $enable = TRUE)
    {
        if( ! validate($brand_sn, 'BRAND_SN') )
        {
            $this->set_error("获取品牌失败：品牌编码[{$brand_sn}]格式不正确。");
            return FALSE;
        }
        
        $where = array(
            'brand_sn'  => $brand_sn,
            'is_delete' => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = BRAND_STATUS_ON;
        }

        $this->load->dao('Brand_dao');
        $brand = $this->Brand_dao->get_one($where);
        if( ! $brand)
        {
            $this->set_error("获取品牌失败：无法找到品牌[{$brand_sn}]。");
            return FALSE;
        }

        return $brand;
    }

    // --------------------------------------------------------------------
    
    /**
     * [新增品牌]
     * @param  [array]  $params [所有信息的数组]
     * @return [bool]
     */
    public function add_brand(Array $params)
    {
        $params = array(
            'brand_sn' => $params['brand_sn'] ? strtoupper(xss_clean($params['brand_sn'])) : NULL,
            'name'     => $params['name']     ? xss_clean(trim($params['name']))           : NULL,
            'name_en'  => $params['name_en']  ? xss_clean(trim($params['name_en']))        : NULL,
        );
        
        $brand    = array();

        // 校验品牌编号
        if( ! validate($params['brand_sn'], 'BRAND_SN') )
        {
            $this->set_error("新增品牌失败：品牌编码[{$params['brand_sn']}]格式不正确。");
            return FALSE;
        }
        // 校验用户名是否存在
        $this->load->dao('Brand_dao');
        $count = $this->Brand_dao->count(array(
            'brand_sn'  => $params['brand_sn'],
            'is_delete' => UNDELETED,
        ));
        if( $count > 0 )
        {
            $this->set_error("新增品牌失败：品牌编码[{$params['brand_sn']}]已存在。");
            return FALSE;
        }
        $brand['brand_sn'] = $params['brand_sn'];

        // 校验中文名
        if( ! validate_length($params['name'], 1, 20) )
        {
            $this->set_error("新增品牌失败：中文名最少1个字最多20个字[{$params['name']}]。");
            return FALSE;
        }
        $brand['name'] = $params['name'];

        // 校验英文名
        if( ! validate_length($params['name_en'], 1, 20) )
        {
            $this->set_error("新增品牌失败：英文名最少1个字最多20个字[{$params['name']}]。");
            return FALSE;
        }
        $brand['name_en'] = $params['name_en'];

        // 写入
        $brand['status']       = BRAND_STATUS_ON;
        $brand['is_delete']    = UNDELETED;
        $brand['create_admin'] = login_info('admin_id');
        $brand['create_time']  = now_str();

        $this->load->dao('Brand_dao');
        if( ! $this->Brand_dao->insert($brand))
        {
            $this->set_error("新增品牌失败：无法写入数据库。");
            return FALSE;
        }

        return $brand['brand_sn'];
    }

    // --------------------------------------------------------------------
    
    /**
     * [编辑品牌]
     * @param  [string] $brand_sn   [品牌编码]
     * @param  [array]  $params     [所有信息的数组]
     * @return [bool]
     */
    public function edit_brand($brand_sn, Array $params)
    {
        if( FALSE === $this->get_brand($brand_sn, TRUE) )
        {
            $this->set_error("编辑品牌失败：无法找到品牌[{$brand_sn}]。");
            return FALSE;
        }

        $brand = array();

        /* 校验中文名开始 */
        if( isset($params['name']) )
        {
            if( ! validate_length($params['name'], 1, 20) )
            {
                $this->set_error("编辑品牌失败：中文名最少1个字最多20个字[{$params['name']}]。");
                return FALSE;
            }
            $brand['name'] = $params['name'];
        }
        /* 校验中文名开始 */

        /* 校验英文名开始 */
        if( isset($params['name_en']) )
        {
            if( ! validate_length($params['name_en'], 1, 20) )
            {
                $this->set_error("编辑品牌失败：英文名最少1个字最多20个字[{$params['name']}]。");
                return FALSE;
            }
            $brand['name_en'] = $params['name_en'];
        }
        /* 校验中文名结束 */

        if( ! $brand )
        {
            $this->set_error("编辑品牌失败：没有需要编辑的内容。");
            return FALSE;
        }

        // 编辑
        $brand['update_admin'] = login_info('admin_id');
        $brand['update_time']  = now_str();

        $where['brand_sn']  = $brand_sn; 
        $where['status']    = BRAND_STATUS_ON; 
        $where['is_delete'] = UNDELETED;

        $this->load->dao('Brand_dao');
        $count = $this->Brand_dao->update(
            $brand,
            $where,
            NULL,
            1
        );
        if( ! ($count > 0) )
        {
            $this->set_error("编辑品牌失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    // --------------------------------------------------------------------
    
    /**
     * [生成where条件]
     * @param  [array] $params
     * @return [array]
     */
    private function _brand_where($params)
    {
        $where = array(
            'is_delete' => UNDELETED,
        );

        if( ! empty($params['brand_sn']) )
        {
            $where['`brand_sn` LIKE'] = "%".xss_clean(trim($params['brand_sn']))."%";
        }

        if( ! empty($params['name']) )
        {
            $where['`name` LIKE'] = "%".xss_clean(trim($params['name']))."%";
        }

        if( ! empty($params['name_en']) )
        {
            $where['`name_en` LIKE'] = "%".xss_clean(trim($params['name_en']))."%";
        }

        if( ! empty($params['status']) )
        {
            $brand_status = $this->config->item('brand_status');
            if( $brand_status["{$params['status']}"] )
                $where['status'] = $params['status'];
        }

        if( ! empty($params['create_time_start']) && strtotime($params['create_time_start']) )
        {
            $where['`create_time` >'] = $params['create_time_start'];
        }

        if( ! empty($params['create_time_end']) && strtotime($params['create_time_end']) )
        {
            $where['`create_time` <'] = $params['create_time_end'];
        }

        if( ! empty($params['update_time_start']) && strtotime($params['update_time_start']) )
        {
            $where['`update_time` >'] = $params['update_time_start'];
        }

        if( ! empty($params['update_time_end']) && strtotime($params['update_time_end']) )
        {
            $where['`update_time` <'] = $params['update_time_end'];
        }
        return $where;
    }

    // --------------------------------------------------------------------
    
    /**
     * [分页浏览]
     * @param  [array]  $params  [条件]
     * @param  [int]    $page    [当前页]
     * @param  [int]    $size    [页数，只允许app_config中"pagesize"的值]
     * @param  [string] $orderby [排序]
     * @return [array]
     */
    public function browse_brand($params, $page = NULL, $size = NULL, $orderby = '`brand_id` DESC')
    {
        $where = $this->_brand_where($params);

        $pagesize = $this->config->item('pagesize');
        $size     = isset($pagesize[$size]) ? $size : 10;
        $offset   = intval(($page-1)*$size) > 0 ? intval(($page-1)*$size) : 0;
        $total    = 0;

        $this->load->dao('Brand_dao');
        $data = $this->Brand_dao->get(
            $where, 
            '*', 
            $orderby, 
            $size, 
            $offset, 
            TRUE, 
            $total
        );
        return array(
            'size' => $size,
            'data' => $data,
            'total'=> $total,
        );
    }

    // --------------------------------------------------------------------
    
    /**
     * [改变状态]
     * 
     * @param  [int]    $brand_sn   [编码]
     * @param  [string] $act        [操作类型]
     * @return [bool]
     */
    public function change_brand_status($brand_sn, $act)
    {   
        if( ! $brand = $this->get_brand($brand_sn, FALSE))
        {
            $this->set_error("修改品牌状态失败：无法找到品牌[{$brand_sn}]。");
            return FALSE;
        }

        // 初始化数据
        $_status       = NULL;  //修改的状态
        $_allow_status = NULL;  //允许修改的状态
        $_update       = NULL;  //更新的数据
        
        switch (strtolower(trim($act)))
        {
            case 'on':
                    $_status       = BRAND_STATUS_ON;
                    $_allow_status = array(BRAND_STATUS_OFF);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            case 'off':
                    $_status       = BRAND_STATUS_OFF;
                    $_allow_status = array(BRAND_STATUS_ON);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            default:
                    $this->set_error("修改品牌状态失败：未知的操作[{$act}]。");
                    return FALSE;
                break;
        }

        $status      = $this->config->item('brand_status');
        $status_name = (string)$status[$_status];

        // 验证状态
        $current_status = (int)$brand['status'];
        if($current_status === $_status)
        {
            $this->set_error("修改品牌状态失败：无需修改。");
            return FALSE;
        }

        if( $_allow_status && ! in_array($current_status, $_allow_status))
        {
            $this->set_error("修改品牌状态失败：不允许被修改为[{$status_name}]状态。");
            return FALSE;
        }

       
        // 只有符合条件才会被修改
        $this->load->dao('Brand_dao');
        $affected_row = $this->Brand_dao->update_in(
            $_update,
            array('status'   => $_allow_status),
            array('brand_sn' => $brand_sn)
        );
        if($affected_row<=0)
        {
            $this->set_error("修改品牌状态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    // --------------------------------------------------------------------
    
    /**
     * [绑定品牌信息]
     * @param  [& array]    列表, 必须包含brand_sn
     * @param  [bool]       是否开启单个模式
     * @param  [string]     列表中`brand_sn`列的键名
     * @return [bool]
     */
    public function wrap_brand_info( & $list, $single_mode = FALSE, $key = 'brand_sn')
    {
        if( ! $list || ! $key ) 
            return FALSE;
        
        switch ($key) 
        {
            case 'brand_sn':
                $col = 'brand_sn';
                break;

            default:
                return FALSE;
                break;
        }



        if($single_mode === TRUE)
        {
            $sn = $list[$key];
            if( ! $sn) 
                return FALSE;

            $this->load->dao('Brand_dao');
            $brand = $this->Brand_dao->get_one(
                array(
                    'is_delete' => UNDELETED,
                    'brand_sn'  => $sn,
                ),
                array(
                    'brand_sn','name','name_en'
                )
            );
            $list['brand_info'] = $brand;
        }
        else
        {
            $sns = array_pick($list, $key);
            if( ! $sns) 
                return FALSE;
            
            // 获取角色信息
            $this->load->dao("Brand_dao");    
            $brand = $this->Brand_dao->get_in(
                array('brand_sn'  => $sns), 
                array('is_delete' => UNDELETED), 
                array('brand_sn','name','name_en')
            );

            array_change_key($brand, 'brand_sn');

            foreach ($list as &$item) 
            {
                $sn                 = $item[$key];
                $item['brand_info'] = isset($brand[$sn]) ? $brand[$sn] : array();
            }
            unset($item);
        }
        
        unset($list);
        return TRUE;
    }
}